<template>
  <div class="app-container">
    <el-row>
      <el-col :span="12">
        <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="城市" prop="city">
        <el-select
          v-model="queryParams.city"
          placeholder="选择城市"
          clearable
          style="width: 240px"
		  @change="handleCity"
        >
          <el-option v-for="(item,index) in cityList" :key="index" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="地区" prop="area">
        <el-select
          v-model="queryParams.area"
          placeholder="选择地区"
          clearable
          style="width: 240px"
          @change="handleCounty"
        >
          <el-option v-for="(item,index) in countyList" :key="index" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="人员" prop="personnel">
        <el-input
          v-model="queryParams.personnel"
          placeholder="请输入人员"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备编号" prop="deviceCode">
        <el-input
          v-model="queryParams.deviceCode"
          placeholder="请输入设备编号"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="noticeList">
      <el-table-column
        label="地区"
        align="center"
        prop="city"
        width="100"
      >
      <template #default="scope">
        {{ scope.row.cityName }}{{ scope.row.areaName }}
      </template>
      </el-table-column>
      <el-table-column
        label="设备名称"
        align="center"
        prop="deviceName"
        width="100"
      />
      <el-table-column
        label="设备唯一编号"
        align="center"
        prop="deviceCode"
        width="160"
      />
      <el-table-column
        label="所属部门"
        align="center"
        prop="department"
        :show-overflow-tooltip="true"
      /> 
       <el-table-column
        label="所属人员"
        align="center"
        prop="personnel"
        width="100"
      />
      <!-- <el-table-column
        label="部门"
        align="center"
        prop="department"
        width="100"
      /> -->
      <!-- <el-table-column
        label="人员"
        align="center"
        prop="personnel"
        width="100"
      /> -->
      <!-- <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          {{ ["归库", "使用中", "维修中", "报废"][scope.row.status] }}
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        width="140"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip content="查看" placement="top">
            <el-button
              link
              type="primary"
              icon="View"
              @click="handleDetail(scope.row)"
              v-hasPermi="['system:notice:edit']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="调拨" placement="top">
            <el-button
              link
              type="primary"
              icon="guide"
              @click="handleExchange(scope.row)"
              v-hasPermi="['system:notice:remove']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="状态变更" placement="top">
            <el-button
              link
              type="primary"
              icon="edit"
              @click="handleStatus(scope.row)"
              v-hasPermi="['system:notice:remove']"
            ></el-button>
          </el-tooltip>
        </template> 
      </el-table-column>-->
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageSize"
      v-model:limit="queryParams.pageCount"
      @pagination="getList"
    />
      </el-col>
      <el-col :span="12">
        <div id="myMap"></div>
      </el-col>
    </el-row>
   

    <!-- 添加 -->
    <el-dialog :title="title" v-model="open" width="560px">
      <el-form ref="noticeRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input disabled v-model="form.deviceName" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="PAD型号" prop="padModel">
              <el-input disabled v-model="form.padModel" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="PAD品牌" prop="padBrand">
              <el-input disabled v-model="form.padBrand" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属部门" prop="departmentId">
              <el-tree-select
                style="width: 100%"
                v-model="form.departmentId"
                :data="organizationTreeList"
                :render-after-expand="false"
                value-key="id"
                :props="{
                  label: 'orgName',
                  children: 'childs',
                }"
                @node-click="changeDepartment"
                v-if="title == '调拨'"
              />
              <el-input disabled v-model="form.department" v-else />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="人员" prop="userId">
              <el-select
                v-model="form.userId"
                placeholder="人员"
                clearable
                v-if="title == '调拨'"
              >
                <el-option
                  :label="item.real_name"
                  :value="item.id"
                  v-for="item in userList"
                  :key="item.id"
                  @click="changeUser(item)"
                />
              </el-select>
              <el-input disabled v-model="form.personnel" v-else />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="状态" clearable>
                <el-option label="归库" value="0" />
                <el-option label="使用中" value="1" />
                <el-option label="维修中" value="2" />
                <el-option label="报废" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 详情 -->
    <el-dialog
      title="查看设备"
      class="scrollbar"
      v-model="detailVisible"
      width="560px"
      append-to-body
    >
      <div class="dialog-content">
        <el-form>
          <el-row>
            <el-col :span="12">
              <el-form-item label="设备名称">
                {{ form.deviceName }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="PAD品牌"> {{ form.padBrand }} </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门"> {{ form.department }} </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="PAD型号"> {{ form.padModel }} </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="人员"> {{ form.personnel }} </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                {{ ["归库", "使用中", "维修中", "报废"][form.status] }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="WebMessage">
import {
  list,
  add,
  getUser,
  getOrganization,
  changeStatus,
  getGridList,
  getCity,
  getCounty
} from "@/api/device/pad";
import { getToken } from "@/utils/auth";
import { toRefs,toRef,toRaw } from "vue";
import { onMounted, reactive, ref } from "vue";
const { proxy } = getCurrentInstance();
const noticeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");
const detailVisible = ref(false);
const organizationTreeList = ref([]);
const userList = ref([]);
const center = ref(null)
const gridList = ref([
  {latitude:30.11985,longitude:120.21963,address:'1111',id:1,deviceName: "联想平板1"},
  {latitude:30.140877,longitude:120.195318,address:'1111',id:2,deviceName: "联想平板2"},
  {latitude:30.161899,longitude:120.271899,address:'1111',id:3,deviceName: "联想平板3"},
  {latitude:30.025176,longitude:120.291348,address:'1111',id:4,deviceName: "联想平板4"},
])
const openMap = ref(true)
const data = reactive({
  form: {},
  queryParams: {
    pageCount: 10,
    pageSize: 1,
    // status: "",
    // department: "",
    // personnel: "",
    // deviceCode: "",
    city:'',
    area:'',
    token:getToken()
  },
  rules: {
    orgIds: [{ required: true, message: "发送对象不能为空", trigger: "blur" }],
    title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
    content: [{ required: true, message: "内容不能为空", trigger: "blur" }],
  },
  deviceInfo:{
    deviceName:'联想平板',
    deviceNum:'7F7C35BD104928757DBD08F3DA95038DB1349B27',
    city:'杭州',
    county:'临平区',
    department:'组织部',
    username:'张三',
    latitude:30.025176,
    longitude:120.291348,
  },
  //设置区域数据
  paths:[
      {
      path:[40.044908, 116.28292, 40.045069, 116.283019, 40.045177, 116.283158, 40.04527, 116.283311, 40.045317, 116.283486],
      styleId:"styel1",
      },
      {
      path:[40.051751, 116.288379, 40.051908, 116.289468, 40.051894, 116.289548, 40.051847, 116.289586, 40.050994, 116.289776, 40.050929, 116.289746, 40.050899, 116.289688],
      styleId:"styel2"
      },
  ],
   options: []
});
let  map = ref(null);
let area = ref(null);
const cityList = ref([]);
const countyList = ref([]);
const newArr = ref([])
const { queryParams, form, rules,deviceInfo,paths,options } = toRefs(data);
// 地图初始化
const initMap = () => {
    //定义地图中心点坐标     
     center.value = new TMap.LatLng(30.241974,120.20874);
    //定义map变量，调用 TMap.Map() 构造函数创建地图
     map.value = new TMap.Map(document.getElementById('myMap'), {
        center: center.value,//设置地图中心点坐标
        zoom: 9,   //设置地图缩放级别
        disableDefaultUI: false,
        viewMode:'2D', //固定上北下南，不可旋转和倾斜
        // mapStyleId: 'style1', //设置地图样式
    });
    // //移除旋转控件
    map.value.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ROTATION)
    console.log('paths',paths.value)
    // console.log(new TMap.visualization)
    //创建区域图
    // setTimeout(()=>{
    //   area.value = new TMap.visualization.Area({
    //     styles: { //设置区域图样式
    //         styel1: {
    //             fillColor: 'rgba(56,124,234,0.8)', //设置区域填充色
    //             strokeColor: '#6799EA' //设置区域边线颜色,
    //         }, 
    //         styel2: {
    //             fillColor: 'rgba(56,124,234,0.5)', //设置区域填充色
    //             strokeColor: '#6799EA' //设置区域边线颜色
    //         },
    //     }
    // }).setData(paths.value).addTo(map.value)
    // console.log('window.area',area)
    // },3000)
      
  }


// 统计发送对象数量
watch(
  () => data.form.orgIds,
  (newValue, oldValue) => {
    console.log(newValue);
    data.form.receNum = newValue.length;
  }
);
/** 查询消息列表 */
function getList() {
  loading.value = true;
  console.log('queryParams',queryParams.value)
  getGridList(queryParams.value).then((response) => {
    noticeList.value = response.data.records;
    total.value = response.data.total;
    // total.value = response.data.length;
    tMapMarker(noticeList.value);
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  proxy.resetForm("noticeRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageSize = 1;
  countyList.value = ''
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
	console.log('proxy',proxy)
  proxy.resetForm("queryRef");
  handleQuery();
}

// 修改所属部门
function changeDepartment(value) {
  form.value.department = value.orgName;
  getUser(value.orgId).then((res) => {
    form.value.userId = "";
    form.value.personnel = "";
    userList.value = res;
  });
}
// 修改人员
function changeUser(value) {
  form.value.personnel = value ? value.real_name : "";
}

/** 调拨操作 */
function handleExchange(row) {
  const ids = row.id;
  // 判断状态
  if (row.status == 1) {
    proxy.$modal
      .confirm("该设备正在使用中，是否确认调拨？？")
      .then(function () {
        reset();
        getOrganization().then((res) => {
          organizationTreeList.value = res;
          form.value = Object.assign({}, row);
          open.value = true;
          title.value = "调拨";
        });
      });
  } else {
    getOrganization().then((res) => {
      organizationTreeList.value = res;
      form.value = Object.assign({}, row);
      open.value = true;
      title.value = "调拨";
    });
    if (row.orgId) {
      getUser(row.orgId).then((res) => {
        userList.value = res;
      });
    }
  }
}

/** 状态变更操作 */
function handleStatus(row) {
  const ids = row.id;
  form.value = Object.assign({}, row);
  // 判断状态
  open.value = true;
  title.value = "状态变更";
}
/**详情 */
function handleDetail(row) {
  form.value = row;
  detailVisible.value = true;
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["noticeRef"].validate((valid) => {
    if (valid) {
      if (title.value == "调拨") {
        add(form.value).then((response) => {
          proxy.$modal.msgSuccess(title.value + "成功");
          open.value = false;
          getList();
        });
      } else {
        changeStatus(form.value).then((response) => {
          proxy.$modal.msgSuccess(title.value + "成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}


//创建marker事件
function createMarker(data) {
  console.log('createMarker',data)
  if (!window.marker) {
    console.log('11')
    window.marker = new TMap.MultiMarker({
      map: map.value, //指定地图容器
      //样式定义
      styles: {
        //创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
        myStyle: new TMap.MarkerStyle({
          width: 30, // 点标记样式宽度（像素）
          height: 40, // 点标记样式高度（像素）
          // src:  "/zooMap/map/" + this.iconName + ".png",
          anchor: { x: 16, y: 32 },
        }),
      },
      //点标记数据数组
      geometries: data,
      zIndex: 10000,
    });
    console.log('marker',window.marker)
    //监听标记点事件
      marker.on("click", function (v) {
        console.log('v',v)
        infoWinClose()
        setInfoWindow();
        window.infoWindow.open();
        let { lat, lng } = v.geometry.position
        setCenter(lat, lng)
        //设置信息框位置
        window.infoWindow.setPosition(v.geometry.position); 
        //设置信息窗内容
        let content = setDetail(v)
        window.infoWindow.setContent(content);
      });
  }
}
function infoWinClose(){
  if(window.infoWindow){
    window.infoWindow.destroy()
  }
}
//初始化window.infoWindow
function setInfoWindow() {
  let center = new TMap.LatLng(31.055170318121824, 121.72260944788603);
  window.infoWindow = new TMap.InfoWindow({
    map: map.value,
    position: center, //设置信息框位置
    content: "Hello World!", //设置信息框内容
  });
  window.infoWindow.close();
}
//设置地图中心点事件
function setCenter(lat, lng) {
 map.value.setCenter(new TMap.LatLng(lat, lng))
}
function setDetail(v){
  console.log('setDetail',v.geometry.deviceName)
  console.log('deviceInfo',deviceInfo)
        let content = `<div class="openMap">
                          <div class="openMap-title">设备信息</div>
                          <div class="openMap-content">
                            <div class="openMap-content-row">
                              <div class="openMap-content-row-col">
                                <div class="col-label">设备号</div>
                                <div class="col-value active">${v.geometry.deviceCode}</div>
                              </div>
                              <div class="openMap-content-row-col">
                                <div class="col-label">设备名称</div>
                                <div class="col-value">${v.geometry.deviceName}</div>
                              </div>
                              <div class="openMap-content-row-col">
                                <div class="col-label">所属市</div>
                                <div class="col-value">${v.geometry.city}</div>
                              </div>
                              <div class="openMap-content-row-col">
                                <div class="col-label">所属县</div>
                                <div class="col-value">${v.geometry.area}</div>
                              </div>
                              <div class="openMap-content-row-col">
                                <div class="col-label">所属部门</div>
                                <div class="col-value">${v.geometry.department?v.geometry.department:''}</div>
                              </div>
                              <div class="openMap-content-row-col">
                                <div class="col-label">所属人员</div>
                                <div class="col-value">${v.geometry.personnel?v.geometry.personnel:''}</div>
                              </div>
                              <div class="openMap-content-row-col">
                                <div class="col-label">经度</div>
                                <div class="col-value">${v.geometry.longitude}</div>
                              </div>
                              <div class="openMap-content-row-col">
                                <div class="col-label">纬度</div>
                                <div class="col-value">${v.geometry.latitude}</div>
                              </div>
                            </div>
                          </div>
                        </div> `;
      return content;
 }

//删除marker
function removeMarker() {
  if (window.marker) {
	window.marker.setMap(null);
	window.marker = null;
  }
}
// 封装marker
function tMapMarker(list) {
	removeMarker();
  const that =this;
  let data = [];
  list.forEach((v) => {
    let obj = {
      id: v.id, //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
      styleId: "myStyle", //指定样式id
      position: new TMap.LatLng(v.latitude, v.longitude), //点标记坐标位置
      properties: {
        //自定义属性
        title: v.id,
      },
      address: v.address,
      deviceName: v.deviceName,
      department: v.department,
      deviceCode:v.deviceCode,
      personnel:v.personnel,
      latitude:v.latitude,
      longitude:v.longitude,
      city:v.cityName,
      area:v.areaName
    };
    console.log('obj',obj)
    data.push(obj);
  });
  //创建并初始化MultiMarker
    createMarker(data);
}
function handleChange(value) {
  console.log('value',value);
}
/** 查询市县 */
function getCitys() {
  getCity().then((response) => {
    cityList.value = response.data;
  });
}
function getCountys(id) {
  console.log('queryParams',queryParams.value)
  getCounty(id).then((response) => {
    countyList.value = response.data;
  });
}
function handleCity(e){
	console.log(e,event)
	console.log(queryParams.value.city)
	const name =  getName(cityList.value,e)
	queryParams.value.city = name
	if(e)getCountys(e)
}
function handleCounty(e){
	const name =  getName(countyList.value,e)
	queryParams.value.area = name
}
function getName(arr,id){
	return  arr.filter((v)=>v.id==id)[0].name
}
onMounted(()=>{
      initMap();
      getList();
	  getCitys()

})
</script>
<style lang="scss" scoped>
.app-container{
  width:100%;height:100%;overflow:hidden;
}
#myMap{
  overflow:hidden;
  width: 100%;
  height: 100vh;
  margin: 0;
  font-family: "微软雅黑";
}

</style>